//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Data.SqlTypes;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;

namespace CommunityServer.Galleries.Controls
{

	public class CategoryListing : GalleryThemedControl
	{

		#region Private Members

		private int columnCount = 0;
		private int rowCount = 0;
		private int totalColumns = 0;
		private bool totalColumnsFound = false;
		private int totalCategories = 0;
		private CSContext cSContext;

		#endregion

		#region Child Controls

		private RepeaterPlusNone Categories;
		private RssButton rssButton;
		private HtmlTableCell footerRow;
		private Pager pager;
		private CurrentPage currentPage;
		private Panel pagerPanel;

		#endregion

		#region Public Properties

		private ArrayList dataSource = null;
		public ArrayList DataSource
		{
			get { return dataSource; }
			set { dataSource = value; }
		}

		[DefaultValue( 2 )]
		public int Columns
		{
			get { return columns; }
			set { columns = value; }
			}
		public int columns = 2;

		[DefaultValue( 3 )]
		public int Rows
		{
			get { return rows; }
			set { rows = value; }
			}
		private int rows = 3;

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			Categories = (RepeaterPlusNone)FindControl( "Categories" );
			rssButton = (RssButton)FindControl( "RssButton" );
			footerRow = FindControl( "FooterRow" ) as HtmlTableCell;
			pager = (Pager) FindControl("Pager");
			currentPage = (CurrentPage) FindControl("CurrentPage");
			pagerPanel = (Panel) FindControl("PagerPanel");
			
			InitializeChildControls();
		}

		private void InitializeChildControls()
		{
			cSContext = CSContext.Current;

			string appKey = cSContext.ApplicationKey;
			Categories.ItemDataBound += new RepeaterItemEventHandler(Categories_ItemDataBound);
			Categories.NoneItemsDataBound += new RepeaterItemEventHandler(Categories_NoneItemsDataBound);

			if (rssButton != null)
			{
				bool isAvailableToPublic = Permissions.ValidatePermissions(CurrentGallery, Permission.View, Users.GetAnonymousUser(true));

				if (CurrentGallery.EnableRss && (isAvailableToPublic || cSContext.SiteSettings.EnableSecureSyndication))
				{
					string title = Globals.HtmlEncode(CurrentGallery.Name);
					string rssCat = Globals.FullPath(GalleryUrls.Instance().Rss(RssType.Categories, appKey));

					if (isAvailableToPublic)
					{
						rssButton.NavigateUrl = rssCat;
						rssButton.IsSecureFeed = false;
					}
					else
					{
						rssButton.NavigateUrl = SiteUrls.FormatUrlWithUserNameToken(rssCat, cSContext.User, false);
						rssButton.IsSecureFeed = true;
					}

					rssButton.ImageUrl = Globals.GetSiteUrls().RssImage(false);
					rssButton.IncludeAutodiscovery = true;
					rssButton.AutoDiscoveryTitle = title;
				}
				else
					rssButton.Visible = false;

			}
			else
			{
				// RssButton control does not exist, so add AutoDiscovery manually
				bool isAvailableToPublic = Permissions.ValidatePermissions(CurrentGallery, Permission.View, Users.GetAnonymousUser(true));
				string title = Globals.HtmlEncode(CurrentGallery.Name);
				string rssCat = Globals.FullPath(GalleryUrls.Instance().Rss(RssType.Categories, appKey));
				if (isAvailableToPublic)
					Head.AddRssAutoDiscovery(title, rssCat, Context);
				else if (cSContext.SiteSettings.EnableSecureSyndication)
					Head.AddRssAutoDiscovery(title, SiteUrls.FormatUrlWithUserNameToken(rssCat, cSContext.User, true), Context);
			}
			
		}


		#endregion

		#region Event Overrides

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			// Get the default columns and rows
			Columns = CurrentGallery.CategoryListingColumns;
			Rows = CurrentGallery.CategoryListingRows;

		}

		protected override void OnLoad(System.EventArgs e)
		{
			base.OnLoad(e);
			DataBind();
		}

		public override void DataBind()
		{
			base.DataBind ();
			BindData();
		}

		#endregion

		private void BindData()
		{
			// If no categories, hide it and return
			/*if((DataSource == null) || (DataSource.Count == 0))
			{
				this.Visible = false;
				return;
			}*/
			if(DataSource == null)
			{
				int categoryID = cSContext.CategoryID > 0 ? cSContext.CategoryID : 0;
				DataSource = PostCategories.GetCategories(CurrentGallery.SectionID, categoryID);
			}

			if(DataSource.Count == 0)
			{
				this.Visible = false;
				return;
			}

			PostCategory.SortBy = CurrentGallery.CategorySortBy;
			DataSource.Sort() ;


			pager.PageIndex = currentPage.PageIndex = cSContext.GetIntFromQueryString("cpage",1)-1; 

			pager.UrlPattern = pager.UrlCleaner(cSContext.RawUrl,"cpage"); 
			pager.PageSize = Columns*Rows;

			
			pager.TotalRecords = currentPage.TotalRecords = totalCategories = DataSource.Count;
			currentPage.TotalPages = pager.CalculateTotalPages();

			if(pagerPanel != null)
			{
				pagerPanel.Visible = (currentPage.TotalPages > 1);
				//pagerPanel.DataBind();
			}



			int pageCount = DataSource.Count;
			pageCount -= (pager.PageIndex)*Columns*Rows;
			if(pageCount > (Columns*Rows))
				pageCount = Columns*Rows;

			// Calculate pagination
			/*
			totalCategories = DataSource.Count;

			// Setup the pagination
			pagination.CurrentPage = CurrentPage;
			pagination.TotalPages = (int)Math.Ceiling( (double)totalCategories / (double)(Columns*Rows) );
			pagination.PrefixText = "page";
			pagination.QueryName = "cpage";
			pagination.NavigateUrl = Page.Request.RawUrl;
			pagination.BindPages();

			*/

			// Grab the items for the current page
			PostCategory[] pageItems = new PostCategory[pageCount];
			DataSource.CopyTo((pager.PageIndex)*Columns*Rows, pageItems, 0, pageCount);

			// Set the datasource and bind
			Categories.DataSource = pageItems;
			Categories.DataBind();

			// Set the footer row colspan
			if(footerRow != null)
				footerRow.ColSpan = totalColumns;
		}

		private void Categories_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			PostCategory dataItem = e.Item.DataItem as PostCategory;

			switch( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:

					HyperLink NameLink = (HyperLink)e.Item.FindControl( "Name" );
					Literal DescLabel = (Literal)e.Item.FindControl( "Description" );
					Literal DateChangedLabel = (Literal)e.Item.FindControl( "DateChanged" );
					Literal TotalPicturesLabel = (Literal)e.Item.FindControl( "TotalPictures" );
					GalleryImage folderImage = (GalleryImage)e.Item.FindControl( "folderImage" );

					if(folderImage != null)
						folderImage.NavigateUrl = GalleryUrls.Instance().ViewCategory(CurrentGallery.ApplicationKey, dataItem.CategoryID);

					if(NameLink != null)
					{
						NameLink.Text = dataItem.Name;
						NameLink.NavigateUrl = GalleryUrls.Instance().ViewCategory(CurrentGallery.ApplicationKey, dataItem.CategoryID);
					}
					
					if(TotalPicturesLabel != null)
						TotalPicturesLabel.Text = dataItem.TotalSubThreads.ToString();

					if (DescLabel != null) 
					{
						if(dataItem.Description != null && dataItem.Description.Length > 50)
							DescLabel.Text = dataItem.Description.Substring(0, 50) + "...";
						else
							DescLabel.Text = dataItem.Description;
						if(DescLabel.Text != string.Empty)
							DescLabel.Text += "<br/>";
					}

					// If there are no posts, the MostRecentPostDate field has a funky value... lets show when the album was created
					if(dataItem.MostRecentSubPostDate <= SqlDateTime.MinValue.Value)
					{
						if (DateChangedLabel != null) 
							DateChangedLabel.Visible = false;
						if(e.Item.FindControl("ChangedTitle") != null)
							e.Item.FindControl( "ChangedTitle" ).Visible = false;
					}
					else
					{
						User user = cSContext.User;
						DateTime changedDate = dataItem.MostRecentSubPostDate;
						string dateFormat;

						if(!user.IsAnonymous)
						{
							changedDate = user.GetTimezone(changedDate);
							dateFormat = user.Profile.DateFormat;
						}
						else
							dateFormat = cSContext.SiteSettings.DateFormat;

						if (DateChangedLabel != null)
							DateChangedLabel.Text = changedDate.ToString(dateFormat);
					}

					// Set column width
					HtmlTableCell tableColumn = e.Item.FindControl("TableColumn") as HtmlTableCell;
					if(tableColumn != null)
						tableColumn.Width = (100 / Columns).ToString() + "%";

					// Begin a column, if necessary
					if(columnCount == 0)
					{
						Literal BeginRowLabel = (Literal)e.Item.FindControl( "BeginRow" );
						BeginRowLabel.Text = "<tr>";
					}
					columnCount++;
					if(!totalColumnsFound)
						totalColumns++;

					// End a column, if necessary
					if((columnCount == Columns) || ((rowCount*Columns+columnCount) == totalCategories))
					{
						Literal EndRowLabel = (Literal)e.Item.FindControl( "EndRow" );
						EndRowLabel.Text = "</tr>";
						columnCount = 0;
						totalColumnsFound = true;
						rowCount++;
					}

					break;
			}
		}

		private void Categories_NoneItemsDataBound(object sender, RepeaterItemEventArgs e)
		{
			Literal NoRecordsLabel = (Literal)e.Item.FindControl( "NoRecords" );
			NoRecordsLabel.Text = ResourceManager.GetString( "ForumMembers_NoRecords" );
		}
	}
}
